package org.onvivals.app.modules.auth.util;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.mapper.UmsUserMapper;
import org.onvivals.module.ums.service.impl.UmsUserServiceImpl;

/**
 * 封装 Sa-Token 常用操作
 *
 * @author 小周周
 * @date 2022/4/21
 */
public class SaTokenUtil {
	/**
	 * 获取登录用户model
	 */
	public static UmsUser getUser() {
		ServiceImpl<UmsUserMapper, UmsUser> impl = SpringUtil.getBean(UmsUserServiceImpl.class);
        return impl.getById(getUserId());
	}

	/**
	 * set用户
	 */
	public static void setUser(UmsUser user) {
		StpUtil.getSession().set("member", user);
	}

	/**
	 * 获取登录用户id
	 */
	public static Long getUserId() {
		return StpUtil.getLoginIdAsLong();
	}

	/**
	 * 获取登录用户name
	 */
	public static String getLoginName() {
		UmsUser user = getUser();
		if (user == null) {
			throw new RuntimeException("用户不存在！");
		}
		return user.getUsername();
	}

	/**
	 * 获取登录用户ip
	 *
	 * @return
	 * @author weirdor
	 */
	public static String getIp() {
		return StpUtil.getTokenSession().getString("login_ip");
	}
}
